import * as path from "path";
import { HttpServer, WsServer } from "tsrpc";
import { getGateConfig, startWatchGateConfig } from "./gateConfigMgr";
import { serviceProto as clientServiceProto } from "./shared/gateClient/protocols/serviceProto";
import { getRedisClient, initRedisClient } from "./shared/tsgfServer/redisHelper";
import { logger } from "./shared/tsgf/logger";
import { GameServerMgr } from "./GameServerMgr";
import { IClusterNodeCfg } from "./shared/tsgfServer/cluster/ClusterMgr";
import { MatchServerMgr } from "./MatchServerMgr";

var gateCfg = startWatchGateConfig();

logger?.log("gateServer.port:", gateCfg.gateServer.port);
const gateServer = new HttpServer(clientServiceProto, {
    port: gateCfg.gateServer.port,
    json: false,
    logger: logger,
});
logger?.log("gameClusterServer.port:", gateCfg.gameClusterServer.port);
const gameServerMgr = new GameServerMgr(() => {
        //每次都从配置中读取
        return getGateConfig().gameServerCfgList.map<IClusterNodeCfg>(c => ({
            nodeId: c.serverId,
            clusterKey: c.clusterKey,
        }));
    },
    {
        port: gateCfg.gameClusterServer.port,
        json: false,
        logger: logger,
    }
);
logger?.log("matchClusterServer.port:", gateCfg.matchClusterServer.port);
const matchServerMgr = new MatchServerMgr(() => {
        //每次都从配置中读取
        return getGateConfig().matchServerCfgList.map<IClusterNodeCfg>(c => ({
            nodeId: c.serverId,
            clusterKey: c.clusterKey,
        }));
    },
    {
        port: gateCfg.matchClusterServer.port,
        json: false,
        logger: logger,
    }
);

async function initServer() {
    await gateServer.autoImplementApi(path.resolve(__dirname, 'api/gateClient'));
};

async function main() {

    if (!gateCfg.redisConfig) {
        logger.error("gf.gate.config.json => redisConfig未配置!");
        return;
    }
    initRedisClient(gateCfg.redisConfig);

    await initServer();
    await gateServer.start();
    logger.log("gate服务启动成功!");
    await gameServerMgr.start();
    logger.log("游戏集群服务启动成功!");
    await matchServerMgr.start();
    logger.log("匹配集群服务启动成功!");

};



main();

